package com.hmdp.utils;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * Redis工具组件
 * @author HeJin
 * @date 2023/01/12 12:36
 */
@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 往Redis存储数据，并设置过期时间
     * @param key 存储key
     * @param object 存储value
     * @param time 过期时间
     * @param unit 时间单位
     */
    public void set(String key, Object object, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(object), time, unit);
    }

    /**
     * 往Redis存储数据，并设置逻辑过期
     * @param key 存储key
     * @param object 存储value
     * @param time 逻辑过期时间
     * @param unit 时间单位
     */
    public void setWithLogicExpire(String key, Object object, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(object);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 解决查询缓存穿透: 缓存null值
     * @param keyPrefix key前缀
     * @param id 对象id
     * @param type 对象Class
     * @param dbFallback 数据库查询语句
     * @param time 过期时间
     * @param unit 时间单位
     * @param <R> 返回类型
     * @param <T> id类型
     * @return R
     */
    public <R, T> R queryWithPassThrough(String keyPrefix, T id, Class<R> type,
                                          Function<T, R> dbFallback,
                                          Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }
        if (Objects.nonNull(json)){
            return null;
        }
        R r = dbFallback.apply(id);
        if (ObjectUtil.isEmpty(r)){
            this.set(key, RedisConstants.CACHE_NULL_VALUE, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        this.set(key, r, time, unit);
        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = new ThreadPoolExecutor(
            10,
            15,
            20, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(),
            ThreadFactoryBuilder.create().build(),
            new ThreadPoolExecutor.AbortPolicy());

    /**
     * 逻辑过期解决缓存穿透查询
     * @param keyPrefix key前缀
     * @param id 对象id
     * @param type 对象类型
     * @param dbFallback 数据查询语句
     * @param time 逻辑过期时间
     * @param unit 时间单位
     * @param <R> 返回类型
     * @param <T> id类型
     * @return R
     */
    public <R, T> R queryWithLogicExpire(String keyPrefix, T id, Class<R> type,
                                          Function<T, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)){
            return null;
        }

        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())){
            return r;
        }

        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock){
            // 获取锁之后再次查询缓存
            json = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(json)){
                redisData = JSONUtil.toBean(json, RedisData.class);
                r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
                expireTime = redisData.getExpireTime();
                if (expireTime.isAfter(LocalDateTime.now())){
                    return r;
                }
            }
            // 缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R r1 = dbFallback.apply(id);
                    this.setWithLogicExpire(key, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });
        }
        return r;
    }

    /**
     * 获取互斥锁
     * @param key key
     * @return boolean
     */
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放互斥锁
     * @param key key
     */
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

}
